<template>
	<div class="set-send">
		<div class="set-send-header bg">
			<el-row type="flex" justify="space-around" class="flex-items-center">
				<el-col :span="6">
					发薪月份：
					<el-date-picker
						v-model="salaryMonth"
						type="month"
						placeholder="选择月"
						value-format="yyyy-MM"
						@change="changeSalaryMonth"
					></el-date-picker>
				</el-col>
				<el-col :span="6">
					发薪类型：
					<el-select v-model="salaryType" placeholder="请选择" @change="handleSalaryTypeChange">
						<el-option
							v-for="item in salaryTypeList"
							:key="item.sstId"
							:label="item.sstName"
							:value="item.sstId"
						>
							<span class="flex-between">
								<span>{{ item.sstName }}</span>
								<span>
									<i
										v-if="item.dataType === 1"
										class="el-icon-close"
										@click.stop.prevent="handleSalaryTypeDelete(item)"
									></i>
								</span>
							</span>
						</el-option>
						<el-option key="-1" label="自定义" value="-1">
							<span class="flex-between">
								<span>自定义</span>
								<span>
									<i class="el-icon-plus" @click.stop.prevent="handleSalaryTypeAppend"></i>
								</span>
							</span>
						</el-option>
					</el-select>
				</el-col>
				<el-col :span="8">
					发薪标题：
					<el-input
						v-model="sendHeader"
						placeholder="请输入发薪标题"
						style="width: 400px;"
					></el-input>
				</el-col>
				<el-col :span="4">本次发送人数： {{ 2 }} 人</el-col>
			</el-row>
		</div>

		<section class="set-send-section">
			<el-row :gutter="20" type="flex" justify="space-around">
				<el-col :span="2" :offset="3">
					<el-card class="user-list" :body-style="{ padding: '0' }">
						<div slot="header">
							<el-input placeholder="姓名" v-model="searchName">
								<el-button slot="append" icon="el-icon-search"></el-button>
							</el-input>
						</div>
						<ul>
							<li
								v-for="item in userList"
								:key="item.userMark"
								:class="{ active: item.userMark === nameActive }"
								@click="nameActive = item.userMark"
							>
								{{ item.userName }}
							</li>
						</ul>
					</el-card>
				</el-col>
				<el-col :span="8">
					<div class="phone-preview">
						<img draggable="false" width="320" src="@/assets/phone.png" alt="phone" />
						<div class="phone-preview-content">
							<phone-preview :content="content" :options="options"></phone-preview>
						</div>
					</div>
				</el-col>
				<el-col :span="10" :pull="2">
					<div class="flex-around">
						<div class="px16 text-bold text-center" style="width: 100px; padding: 10px;">
							工资项
						</div>
						<div class="flex1">
							<el-card class="pay-slip-option" :body-style="{ padding: '0' }">
								<div class="option-list">
									<p class="text-bold">应发工资</p>
									<el-checkbox-group v-model="paySlipOption">
										<el-checkbox
											v-for="item in slipDataOptins"
											:key="item.title"
											:label="`${item.title}_${item.value}`"
										>
											{{ item.title }}
										</el-checkbox>
									</el-checkbox-group>
								</div>
							</el-card>
							<div class="pay-slip-checked">
								<el-checkbox v-model="hideEmpty" :true-label="0" :false-label="1">
									隐藏为“空”数据项
								</el-checkbox>
								<el-checkbox v-model="hideZero" :true-label="0" :false-label="1">
									隐藏为“0”数据项
								</el-checkbox>
							</div>

							<div class="pay-slip-checked">
								<span class="vertical-middle">
									阅后即焚：
								</span>
								<el-switch
									v-model="isBurnAfterReading"
									active-color="#13ce66"
									inactive-color="#ff4949"
									active-value="100"
									inactive-value="0"
								></el-switch>
								<el-input
									v-model.number="burnAfterReading"
									:disabled="!isBurnAfterReading"
									style="width: 100px; margin: 0 20px;"
								>
									<template slot="append">
										<el-select v-model="burnAfterReadingUnit" style="width: 60px;">
											<el-option label="次" :value="1"></el-option>
										</el-select>
									</template>
								</el-input>
								<el-popover placement="bottom-start" width="300" trigger="hover">
									1.超出设置时长/次数后，员工将无法查看详情;
									<br />
									2.工资条焚毁后，不再为员工推送确认提醒;
									<br />
									3.工资条焚毁后次日，确认状态变为已焚毁确认。
									<i class="el-icon-question vertical-middle px16" slot="reference"></i>
								</el-popover>
							</div>

							<div class="pay-slip-checked">
								<el-checkbox v-model="isThanks">感谢语</el-checkbox>
								<el-select
									v-model="thanksStart"
									:disabled="!isThanks"
									style="width: 100px; margin: 0 10px;"
									@change="handleThanksChange"
								>
									<el-option
										v-for="item in thanksList"
										:key="item.id"
										:label="item.thanks"
										:value="item.id"
									>
										<span class="flex-between">
											<span>{{ item.thanks }}</span>
											<span>
												<i
													v-if="item.dataType === 1"
													class="el-icon-close"
													@click.stop.prevent="handleThanksDelete(item)"
												></i>
											</span>
										</span>
									</el-option>
									<el-option key="-1" label="自定义" value="-1">
										<span class="flex-between">
											<span>自定义</span>
											<span>
												<i class="el-icon-plus" @click.stop.prevent="handleThanksAppend"></i>
											</span>
										</span>
									</el-option>
								</el-select>
								<span>+ 姓名 +</span>
								<el-input
									v-model="thanksEnd"
									:disabled="!isThanks"
									style="width: 200px; margin-left: 10px;"
								></el-input>
							</div>
							<div class="pay-slip-checked">
								<el-checkbox v-model="isWarmTips">温馨提示</el-checkbox>
								<el-input
									v-model="warmTips"
									:rows="1"
									:disabled="!isWarmTips"
									type="textarea"
									style="width: 360px; margin-left: 10px;"
								></el-input>
							</div>
						</div>
					</div>
					<div class="flex-around">
						<div class="px16 text-bold text-center" style="width: 100px; padding: 10px;">
							发送方式
						</div>
						<div class="flex1">
							<el-checkbox v-model="sendingMethod" style="margin: 8px auto;" disabled border>
								企业微信
							</el-checkbox>
							&nbsp; &nbsp;
							<el-button type="text" @click="handleChoose">选择模板</el-button>
						</div>
					</div>
				</el-col>
			</el-row>
		</section>

		<div class="setsend-footer flex-center">
			<el-button
				type="primary"
				size="lager"
				@click="$router.push('/sendPaySlip/paySlipDataValidation')"
			>
				上一步
			</el-button>
			<el-button type="primary" size="lager" @click="handleSave">保存</el-button>
			<el-button type="primary" size="lager" @click="handleSend">发送</el-button>
		</div>

		<el-dialog title="选择模板" :visible.sync="dialogVisible" width="50%">
			<el-row :gutter="30">
				<el-col :span="12">
					<el-scrollbar class="salary-template">
						<ul>
							<li v-for="{ index } in 10" :key="index"></li>
						</ul>
					</el-scrollbar>
				</el-col>
				<el-col :span="12"></el-col>
			</el-row>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="dialogVisible = false">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import PhonePreview from './PhonePreview'

import { formatTime } from '@/methods/utils'

import {
	postSalaryTypeSelect,
	postSalaryTypeInsert,
	postSalaryTypeDelete,
	postThanksSelect,
	postThanksInsert,
	postThanksDelete,
	postPayrollAddSave
} from '@/APIs/index/index'
import { mapState } from 'vuex'

export default {
	name: 'PaySlipSetSend',
	components: { PhonePreview },
	props: {
		slipData: {
			type: Array,
			default: () => []
		}
	},
	data() {
		const currentMonth = formatTime(new Date().getTime(), '-').substring(0, 7)
		return {
			active: 3,
			nameActive: null,
			paySlipOption: [], // 选中
			hideEmpty: 1,
			hideZero: 1,
			salary: 1,
			salaryTypeList: [],
			thanksId: 1,
			thanksList: [],
			sendHeader: currentMonth.replace('-', '年') + '月薪资',
			salaryMonth: currentMonth,
			isBurnAfterReading: true,
			burnAfterReading: 1,
			burnAfterReadingUnit: 1,
			sendingMethod: true,
			searchName: '',
			salaryType: 1,
			isThanks: true,
			thanksStart: 1,
			thanksEnd: '感谢您的辛勤付出',
			isWarmTips: true,
			warmTips: '工资条属于敏感信息，请注意保密',
			whetherToSend: false,
			dialogVisible: false
		}
	},
	computed: {
		...mapState(['importType']),
		userList() {
			return this.slipData.length > 0
				? this.slipData.map(item => ({
						userName: (item.find(({ title }) => ['姓名'].includes(title)) || {})?.['value'],
						userMark: (item.find(({ title }) => ['手机号码', '企业微信帐号'].includes(title)) ||
							{})?.['value']
				  }))
				: []
		},
		currentUserSlipData() {
			return this.slipData.length > 0
				? this.slipData.find(
						item =>
							(item.find(({ title }) => ['手机号码', '企业微信帐号'].includes(title)) || {})?.[
								'value'
							] === this.nameActive
				  ) || []
				: []
		},
		slipDataOptins() {
			return this.currentUserSlipData.filter(
				({ title }) => !['姓名', '实发工资', '手机号码', '企业微信帐号'].includes(title)
			)
		},
		content() {
			return {
				username: (this.currentUserSlipData.find(({ title }) => ['姓名'].includes(title)) || {})?.[
					'value'
				],
				sendHeader: this.sendHeader,
				burnAfterReading: this.burnAfterReading,
				sendingMethod: '企业微信',
				salaryMonth: this.salaryMonth,
				salaryType: this.salaryType,
				thanksStart: (this.thanksList.find(({ id }) => id === +this.thanksStart) || {})?.['thanks'],
				thanksEnd: this.thanksEnd,
				warmTips: this.warmTips,
				whetherToSend: this.whetherToSend,
				hideEmpty: this.hideEmpty,
				hideZero: this.hideZero,
				actualSalary: (this.currentUserSlipData.find(({ title }) => ['实发工资'].includes(title)) ||
					{})?.['value']
			}
		},
		options() {
			return this.slipDataOptins
				.filter(({ title }) => this.paySlipOption.some(item => item.split('_')[0] === title))
				.filter(({ value }) => !(value + '' === 'null' && +this.hideEmpty === 0))
				.filter(({ value }) => !(+value === 0 && +this.hideZero === 0))
		}
	},
	watch: {
		slipDataOptins(val) {
			this.paySlipOption = val.map(({ title, value }) => `${title}_${value}`)
		}
	},
	created() {
		const { value = null } =
			(this.slipData[0] || []).find(({ title }) => ['手机号码', '企业微信帐号'].includes(title)) ||
			{}
		this.nameActive = value
		this.getSalaryTypeSelectData()
		this.getThanksSelectData()
	},
	methods: {
		// 发薪类型
		async getSalaryTypeSelectData() {
			const { data } = await postSalaryTypeSelect()
			this.salaryTypeList = data
		},
		// 感谢语句
		async getThanksSelectData() {
			const { data } = await postThanksSelect()
			this.thanksList = data
		},
		// 改变月份
		changeSalaryMonth(val) {
			this.sendHeader = val.replace('-', '年') + '月薪资'
		},
		// 添加发薪类型
		handleSalaryTypeAppend() {
			this.$prompt('请输入自定义发薪类型', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /^\S+/g,
				inputErrorMessage: '请输入自定义发薪类型',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true
						instance.confirmButtonText = '添加中...'
						try {
							const { inputValue: sstName } = instance
							const { data } = await postSalaryTypeInsert({ sstName })
							this.salaryTypeList.push({ ...data })
							this.$message({ type: 'success', message: '添加成功' })
							instance.confirmButtonLoading = false
							done()
						} catch (error) {
							instance.confirmButtonLoading = false
							done()
							throw new Error(error)
						}
					} else {
						done()
					}
				}
			})
		},
		// 删除发薪类型
		handleSalaryTypeDelete(data) {
			this.$confirm('确定删除, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const { sstId } = data
				await postSalaryTypeDelete({ sstId })
				this.salaryTypeList = this.salaryTypeList.filter(item => item?.sstId !== sstId)
				this.$message({ type: 'success', message: '删除成功!' })
			})
		},
		// 发薪类型
		handleSalaryTypeChange(val) {
			if (val + '' === '-1') {
				this.salary = ''
				this.handleSalaryTypeAppend()
			}
		},
		// 添加感谢语句
		handleThanksAppend() {
			this.$prompt('请输入自定义感谢语', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				inputPattern: /^\S+/g,
				inputErrorMessage: '请输入自定义感谢语',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true
						instance.confirmButtonText = '添加中...'
						try {
							const { inputValue: thanks } = instance
							const { data } = await postThanksInsert({ thanks })
							this.thanksList.push({ ...data })
							this.$message({ type: 'success', message: '添加成功' })
							instance.confirmButtonLoading = false
							done()
						} catch (error) {
							instance.confirmButtonLoading = false
							done()
							throw new Error(error)
						}
					} else {
						done()
					}
				}
			})
		},
		// 删除感谢语
		handleThanksDelete(data) {
			this.$confirm('确定删除, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(async () => {
				const { id } = data
				await postThanksDelete({ id })
				this.thanksList = this.thanksList.filter(item => item?.id !== id)
				this.$message({ type: 'success', message: '删除成功!' })
			})
		},
		// 感谢语句
		handleThanksChange(val) {
			if (val + '' === '-1') {
				this.thanksId = ''
				this.handleThanksAppend()
			}
		},
		handleSave() {
			this.whetherToSend = false
			this.postPayrollAddSaveData()
		},
		handleSend() {
			this.whetherToSend = true
			this.postPayrollAddSaveData()
		},
		async postPayrollAddSaveData() {
			if (this.sendHeader === '') {
				this.$message.info('请输入发薪标题')
				return
			}
			if (this.salaryMonth === '') {
				this.$message.info('请选择发薪月份')
				return
			}
			const paramsData = {
				sendHeader: this.sendHeader,
				burnAfterReading: this.burnAfterReading,
				// sendingMethod: this.sendingMethod,
				sendingMethod: '企业微信',
				salaryMonth: this.salaryMonth + '-00',
				salaryType: this.salaryType,
				thanksStart: this.thanksStart,
				thanksEnd: this.thanksEnd,
				warmTips: this.warmTips,
				whetherToSend: this.whetherToSend,
				hideEmpty: this.hideEmpty,
				hideZero: this.hideZero
			}
			if (!this.isBurnAfterReading) delete paramsData.burnAfterReading
			if (!this.isWarmTips) delete paramsData.warmTips
			if (!this.isThanks) delete paramsData.thanksStart
			if (!this.isThanks) delete paramsData.thanksEnd
			await postPayrollAddSave({ ...paramsData })
			this.$router.push(`paySlipManagement`)
		},
		handleChoose() {
			this.dialogVisible = true
		}
	}
}
</script>

<style lang="scss" scoped>
.set-send {
	.set-send-header {
		margin: 0 auto;
		padding: 10px 20px;
		&.bg {
			background-color: #ebf2f8;
			border-radius: 4px;
		}
	}
	.set-send-section {
		margin: 30px auto;
		.phone-preview {
			position: relative;
			.phone-preview-content {
				position: absolute;
				border-radius: 4px;
				width: 280px;
				top: 70px;
				left: 20px;
			}
		}
		.user-list {
			ul {
				height: 600px;
				overflow-y: auto;
				li {
					padding: 10px 20px;
					border: 1px solid transparent;
					border-left: 4px solid transparent;
					cursor: pointer;
					&.active {
						border: 1px solid #c4cdd6;
						border-left: 4px solid #79abd2;
						box-shadow: 0px 0px 8px rgba(66, 121, 172, 0.2);
					}
				}
			}
		}
		.pay-slip-option {
			.option-list {
				height: 425px;
				overflow-y: auto;
				padding: 10px;
				.el-checkbox-group {
					display: flex;
					flex-direction: column;
					.el-checkbox {
						padding: 10px;
					}
				}
			}
			.option-footer {
				border-top: 1px solid #dedede;
				padding: 20px;
			}
		}
		.pay-slip-checked {
			padding: 10px;
		}
	}
	.setsend-footer {
		margin: 80px auto;
	}
}
</style>

<style lang="scss">
.user-list {
	.el-card__header {
		padding: 0px;
	}
}
</style>
